package com.xiaobai.wechat.util;


import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xiaobai.wechat.response.WechatResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author feng
 */
@Slf4j
@Component
public class WechatUtil {

    @Autowired
    private RedisUtil redisUtil;

    @Value("${wechat.appId}")
    private String appId;
    @Value("${wechat.appSecret}")
    private String appSecret;

    private final String TOKEN_KEY = "wechat_token";

    public String getToken() {
        if (redisUtil.hasKey(TOKEN_KEY)) {
            return String.valueOf(redisUtil.get(TOKEN_KEY));
        }
        Map<String, Object> paramMap = new HashMap<>(2);
        paramMap.put("grant_type", "client_credential");
        paramMap.put("appid", appId);
        paramMap.put("secret", appSecret);

        JSONObject jsonObject = JSON.parseObject(HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token", paramMap));
        Object accessToken = jsonObject.get("access_token");
        Object expiresIn = jsonObject.get("expires_in");
        redisUtil.set(TOKEN_KEY, accessToken, Long.parseLong(String.valueOf(expiresIn)));
        return String.valueOf(accessToken);
    }

    public String menuCreate(String postJson) {
        WechatResponse response = JSON.parseObject(HttpUtil.post("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + getToken(), postJson), WechatResponse.class);
        log.info(JSON.toJSONString(response));
        return JSON.toJSONString(response);
    }
}
